import lodash from "lodash";
import dayjs from "dayjs";

//模拟sleep
async function sleep(seconds = 0){
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve('end');
        }, seconds);
    })
}


/**
 * 通过精致token获取登录用户信息
 * @param token | null
 * @returns 用户信息
 */
const getUserInfoByToken = (token = null) => {
    const isDevelopment = import.meta.env.DEV;
    if(token === null) {
        if(isDevelopment){
            token = process.env.VUE_APP_APPLICATION_TOKEN;
        } else {
            token = localStorage.getItem("Token");
        }
    }
    const strings = token.split('.');
    const userInfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, '+').replace(/_/g, '/')))));
    return userInfo;
}

//产生随机数
const getRandom = () => {
    const timeStamp = new Date().getTime();
    let random = Math.random() * 1000;
    random = random < 100 ? random + 100 : random;
    return parseInt(timeStamp + '' + random);
}

//useVbenVxeGrid表格表头自定义筛选的参数处理
const dealVxeGridFilterParameter = (filterListInfo:Object[]):Object => {
    const dealObj = {};
    if(!filterListInfo.length){
        return dealObj;
    }
    for(let i = 0; i < filterListInfo.length; i ++){
        const { column, field, property, values, datas } = filterListInfo[i];
        const filterType = column.filterRender.name;
        let checkDatas = datas.every(da => da === "" || da === undefined || da === null);
        if(!checkDatas){
            if(datas && datas.length === 1 && datas[0] instanceof Array){
                dealObj['startDate'] = datas[0][0];
                dealObj['endDate'] = datas[0][1];
            } else {
                const parameterStr = datas.join(',');
                dealObj[field] = parameterStr;
            }
        } else {
            const parameterStr = values.join(',');
            dealObj[field] = parameterStr;
        }
    }
    return dealObj;
}

//格式化时间
function formatDate(val,type){
    let date = val === null ? new Date() : new Date(val);
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let h = date.getHours();
    let m = date.getMinutes();
    let s = date.getSeconds();
    if(type === 0){
        return year + "-" + addZero(month) + "-" + addZero(day) + " " + addZero(h) + ":" + addZero(m) + ":" + addZero(s);
    } else if (type === 1){
        return year + "-" + addZero(month) + "-" + addZero(day);
    } else if (type === 2){
        return addZero(h) + ":" + addZero(m) + ":" + addZero(s);
    } else if (type === 3){
        return year + "-" + addZero(month) + "-" + addZero(day) + " 00:00:00";
    }
}

function addZero(val){
    return val > 9 ? val : "0" + val;
}


export {
    sleep,
    getUserInfoByToken,
    getRandom,
    dealVxeGridFilterParameter,
    lodash,
    dayjs
}